/*
 * HttpMidlet.java
 *
 * Created on October 23, 2001, 11:19 AM
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;


/**
 *
 * @author  kgabhart
 * @version 
 */
public class HttpMidlet extends MIDlet implements CommandListener {
    // A default URL is used. User can change it from the GUI
    private static String       defaultURL = "http://localhost:8080/test/servlet/EchoServlet";
    
    // Main MIDP display
    private Display             myDisplay = null;
    
    // GUI component for entering a URL
    private Form                requestScreen;
    private TextField           requestField;
    
    // GUI component for submitting request
    private List                list;
    private String[]            menuItems;
    
    // GUI component for displaying server responses
    private Form                resultScreen;
    private StringItem          resultField;
    
    // the "send" button used on requestScreen
    Command sendCommand;
    // the "exit" button used on the requestScreen
    Command exitCommand;
    // the "back" button used on resultScreen
    Command backCommand;
    
    public HttpMidlet(){
        // initialize the GUI components
        myDisplay = Display.getDisplay( this );
        sendCommand = new Command( "SEND", Command.OK, 1 );
        exitCommand = new Command( "EXIT", Command.OK, 1 );
        backCommand = new Command( "BACK", Command.OK, 1 );
        
        // display the request URL
        requestScreen = new Form( "Type in a URL:" );
        requestField = new TextField( null, defaultURL, 100, TextField.URL );
        requestScreen.append( requestField );
        requestScreen.addCommand( sendCommand );
        requestScreen.addCommand( exitCommand );
        requestScreen.setCommandListener( this );
        
        // select the HTTP request method desired
        menuItems = new String[] {"GET Request", "POST Request"};    
        list = new List( "Select an HTTP method:", List.IMPLICIT, menuItems, null );
        list.setCommandListener( this );
        
        // display the message received from server
        resultScreen = new Form( "Server Response:" );
        resultScreen.addCommand( backCommand );
        resultScreen.setCommandListener( this );
            
    }//end HttpMidlet()
    
    public void startApp() {
        myDisplay.setCurrent( requestScreen );
    }//end startApp()
    
    public void commandAction( Command com, Displayable disp ) {
        // when user clicks on the "send" button
        if ( com == sendCommand ) {
            myDisplay.setCurrent( list );
        } else if ( com == backCommand ) {
            // do it all over again
            requestField.setString( defaultURL );
            myDisplay.setCurrent( requestScreen );
        } else if ( com == exitCommand ) {
            destroyApp( true );
            notifyDestroyed();
        }//end if ( com == sendCommand )
        
        if ( disp == list && com == List.SELECT_COMMAND ) {
            
            String result;
            
            if ( list.getSelectedIndex() == 0 ) // send a GET request to server
              result = sendHttpGet( requestField.getString() );
            else // send a POST request to server
              result = sendHttpPost( requestField.getString() );
                    
            resultField = new StringItem( null, result );
            resultScreen.append( resultField );
            myDisplay.setCurrent( resultScreen );
        }//end if ( dis == list && com == List.SELECT_COMMAND )
    }//end commandAction( Command, Displayable )
    
    private String sendHttpGet( String url )
    {
        HttpConnection      hcon = null;
        DataInputStream     dis = null;
        StringBuffer        responseMessage = new StringBuffer();
        
        try {
            // a standard HttpConnection with READ access
            hcon = ( HttpConnection )Connector.open( url );
            
            // obtain a DataInputStream from the HttpConnection
            dis = new DataInputStream( hcon.openInputStream() );
            
            // retrieve the response from the server
            int ch;
            while ( ( ch = dis.read() ) != -1 ) {
                responseMessage.append( (char) ch );
            }//end while ( ( ch = dis.read() ) != -1 )
        }         
        catch( Exception e )
        {
            e.printStackTrace();
            responseMessage.append( "ERROR" );
        } finally {
            try {
                if ( hcon != null ) hcon.close();
                if ( dis != null ) dis.close();
            } catch ( IOException ioe ) {
                ioe.printStackTrace();
            }//end try/catch 
        }//end try/catch/finally
        return responseMessage.toString();
    }//end sendHttpGet( String )
    
    private String sendHttpPost( String url )
    {
        HttpConnection      hcon = null;
        DataInputStream     dis = null;
        DataOutputStream    dos = null;
        StringBuffer        responseMessage = new StringBuffer();
        // the request body
        String              requeststring = "This is a POST.";

        try {
            // an HttpConnection with both read and write access
            hcon = ( HttpConnection )Connector.open( url, Connector.READ_WRITE );

            // set the request method to POST
            hcon.setRequestMethod( HttpConnection.POST );

            // obtain DataOutputStream for sending the request string
            dos = hcon.openDataOutputStream();
            byte[] request_body = requeststring.getBytes();

            // send request string to server
            for( int i = 0; i < request_body.length; i++ ) {
                dos.writeByte( request_body[i] );
            }//end for( int i = 0; i < request_body.length; i++ )

            // obtain DataInputStream for receiving server response
            dis = new DataInputStream( hcon.openInputStream() );

            // retrieve the response from server
            int ch;
            while( ( ch = dis.read() ) != -1 ) {
                responseMessage.append( (char)ch );
            }//end while( ( ch = dis.read() ) != -1 ) {
        }
        catch( Exception e )
        {
            e.printStackTrace();
            responseMessage.append( "ERROR" );
        } 
        finally {
            // free up i/o streams and http connection
            try {
                if( hcon != null ) hcon.close();
                if( dis != null ) dis.close();
                if( dos != null ) dos.close();
            } catch ( IOException ioe ) {
                ioe.printStackTrace();
            }//end try/catch 
        }//end try/catch/finally
        return responseMessage.toString();
    }//end sendHttpPost( String )
    
    public void pauseApp() {
    }//end pauseApp()

    public void destroyApp( boolean unconditional ) {
        // help Garbage Collector
        myDisplay = null;
        requestScreen = null;
        requestField = null;
        resultScreen = null;
        resultField = null;
    }//end destroyApp( boolean )
}//end HttpMidlet